#!/bin/bash

# ============================================
# 服务器端初始化脚本
# ============================================

set -e

# 颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 配置变量
FRONTEND_DIR="/var/www/frontend"
BACKEND_DIR="/opt/backend"
NGINX_CONF_DIR="/etc/nginx/conf.d"

# 步骤1：创建目录
echo_info "步骤1: 创建目录..."
sudo mkdir -p $FRONTEND_DIR
sudo mkdir -p $BACKEND_DIR/media
sudo chown -R $USER:$USER $FRONTEND_DIR
sudo chown -R $USER:$USER $BACKEND_DIR

echo_info "目录创建完成:"
echo_info "  前端目录: $FRONTEND_DIR"
echo_info "  后端目录: $BACKEND_DIR"

# 步骤2：安装 Nginx
echo_info "步骤2: 检查 Nginx..."
if ! command -v nginx &> /dev/null; then
    echo_warn "Nginx 未安装，正在安装..."
    if [ -f /etc/redhat-release ]; then
        # CentOS/RHEL
        sudo yum install -y nginx
    elif [ -f /etc/debian_version ]; then
        # Ubuntu/Debian
        sudo apt-get update
        sudo apt-get install -y nginx
    else
        echo_error "无法识别系统类型，请手动安装 Nginx"
        exit 1
    fi
    echo_info "Nginx 安装完成"
else
    echo_info "Nginx 已安装"
fi

# 步骤3：配置 Nginx
echo_info "步骤3: 配置 Nginx..."
echo_warn "请将 Nginx 配置文件复制到 $NGINX_CONF_DIR/frontend.conf"
echo_warn "然后执行以下命令:"
echo_warn "  sudo nginx -t"
echo_warn "  sudo systemctl reload nginx"

# 步骤4：启动 Nginx
echo_info "步骤4: 启动 Nginx..."
sudo systemctl enable nginx
sudo systemctl start nginx

if sudo systemctl is-active --quiet nginx; then
    echo_info "Nginx 启动成功"
else
    echo_error "Nginx 启动失败"
    exit 1
fi

# 步骤5：配置防火墙
echo_info "步骤5: 配置防火墙..."
if command -v firewall-cmd &> /dev/null; then
    # CentOS/RHEL
    echo_info "配置 firewalld..."
    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
    echo_info "防火墙配置完成"
elif command -v ufw &> /dev/null; then
    # Ubuntu/Debian
    echo_info "配置 ufw..."
    sudo ufw allow 80/tcp
    sudo ufw allow 443/tcp
    sudo ufw reload
    echo_info "防火墙配置完成"
else
    echo_warn "未检测到防火墙工具，请手动配置防火墙"
fi

# 步骤6：显示状态
echo_info "步骤6: 检查服务状态..."
echo_info "Nginx 状态:"
sudo systemctl status nginx --no-pager -l

echo_info "============================================"
echo_info "服务器初始化完成！"
echo_info "============================================"
echo_info "前端目录: $FRONTEND_DIR"
echo_info "后端目录: $BACKEND_DIR"
echo_info "Nginx 配置目录: $NGINX_CONF_DIR"
echo_info "============================================"
echo_warn "下一步操作:"
echo_warn "1. 将前端文件上传到 $FRONTEND_DIR"
echo_warn "2. 将 Nginx 配置文件复制到 $NGINX_CONF_DIR/frontend.conf"
echo_warn "3. 修改配置文件中的域名和路径"
echo_warn "4. 执行: sudo nginx -t && sudo systemctl reload nginx"
echo_info "============================================"

